package com.atguigu.utils;

import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Configuration
@EnableConfigurationProperties(MinioProperties.class)
public class MinioUploader {
    /**
     * 注意： 代码从上往下执行，，minioClient需要miniosProperties的属性（配置文件）
     *  会报 空指针 所以  顺序  “优先加载 配置类，后加载配置文件" ”谁使用谁，会有先后顺序“
     */
    @Autowired
    private MinioProperties minioProperties;

     @Autowired
    private MinioClient minioClient;
    @Bean
    public MinioClient minioClient() throws Exception {
        //使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
        MinioClient minioClient = new MinioClient(minioProperties.getEndpoint(),minioProperties.getAccessKey(), minioProperties.getSecretKey());
        //检查存储桶是否已经存在---是否创建了数据库
        boolean isExist = minioClient.bucketExists(minioProperties.getBucketName());
        if(isExist) {
            System.out.println("Bucket already exists.");
        } else {
            //创建一个名为asiatrip的存储桶，用于存储照片的zip文件。
            minioClient.makeBucket(minioProperties.getBucketName());
        }
        return minioClient;
    }

    public  String  uploader(MultipartFile multipartFile) throws Exception {
            String fileName = UUID.randomUUID().toString().replaceAll("-","").substring(0,6) + multipartFile.getOriginalFilename();
            //1.文件放到哪个桶里面  2.文件上传成功之后名称叫什么 3.文件流 4.文件参数设置
            InputStream inputStream = multipartFile.getInputStream();

            PutObjectOptions putObjectOptions = new PutObjectOptions(inputStream.available(), -1);
            putObjectOptions.setContentType(multipartFile.getContentType());
            minioClient.putObject(minioProperties.getBucketName(),fileName, inputStream,putObjectOptions);
            System.out.println("上传成功");
            //http://172.18.0.2:9000/java0212/new.jpg
           String url=minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+fileName;
           return url;
    }
}
